# coding=utf-8

from subprocess import Popen, STDOUT, PIPE
import re

def ping_cmd(ip_addr) :
    s = Popen('ping -c 1 -t 1 {}'.format(ip_addr), stderr=STDOUT, stdout=PIPE, shell=True)
    s.wait()
    result = s.stdout.read()

    pattern = re.compile('time=([-+]?[0-9]*\.?[0-9]*) ms')
    m = pattern.findall(result)
    if len(m) == 0:
        print('{} time out'.format(ip_addr))
        return (10000, ip_addr)
    else:
        print('{} for {}ms'.format(ip_addr, m[0]))
        return (float(m[0]), ip_addr)

def find_fast(ip_addr_list):
    time_list = map(ping_cmd, ip_addr_list)
    min_time = 10000
    min_ip = ''
    for time, ip in time_list:
        if time < min_time:
            min_time = time
            min_ip = ip
    return (min_time, min_ip)

def sort_fast(ip_addr_list):
    time_list = map(ping_cmd, ip_addr_list)
    result = sorted(time_list, key=lambda item: item[0])
    return result


prefix_list = ['j0', 'j1', 'j2', 'j3', 'j4', 'j5', 'us0', 'us1', 'us2', 'us3', 'us4', 'us5', 'us6',
               'us7', 'us8', 'us9', 'hk', 'sg01', 'uk']

def fill_prefix(prefix):
    return '{}.0bad.com'.format(prefix)

ip_list = map(fill_prefix, prefix_list)


# m = find_fast(ip_list)
# print('the most fast server is {}, used {} ms'.format(m[1], m[0]))

result = sort_fast(ip_list)
print('\n\n\n\n\n\n>>>sorted result:')
for item in result:
    speed = item[0] if item[0] != 10000 else '--'
    addr = item[1]
    print('{} - {}ms'.format(addr, speed))


# def fave_list():
#     line = u'''
#     <DL><p>
#             <DT><A HREF="http://www.37zy.net/">37资源网</A>
#         </DL><p>
#
#     '''
#
#     pattern = re.compile(u'<A HREF="http[s]?://(.+)/(.*)">')
#     m = pattern.findall(line)
#
#     def pure_address(item):
#         return item[0]
#
#     pm = map(pure_address, m)
#     return pm
#
#
# list = fave_list()
# for item in list:
#     res = ping_cmd(item)
#     if res[0] < 10000:
#         print(res)
